import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { message } from 'ant-design-vue'
import { userApi } from '@/api/user'
import type { LoginUserVO, UserLoginRequest, UserRegisterRequest } from '@/types/user'

export const useUserStore = defineStore('user', () => {
  // 状态
  const loginUser = ref<LoginUserVO | null>(null)
  const loading = ref(false)

  // 初始化时尝试从localStorage恢复用户信息
  const initUserFromStorage = () => {
    try {
      const storedUser = localStorage.getItem('loginUser')
      if (storedUser) {
        loginUser.value = JSON.parse(storedUser)
      }
    } catch (error) {
      console.error('恢复用户信息失败:', error)
      localStorage.removeItem('loginUser')
    }
  }

  // 保存用户信息到localStorage
  const saveUserToStorage = (user: LoginUserVO | null) => {
    if (user) {
      localStorage.setItem('loginUser', JSON.stringify(user))
    } else {
      localStorage.removeItem('loginUser')
    }
  }

  // 计算属性
  const isLogin = computed(() => !!loginUser.value?.id)
  const isAdmin = computed(() => loginUser.value?.userRole === 'admin')

  // 获取当前登录用户信息
  const fetchLoginUser = async () => {
    try {
      loading.value = true
      const response = await userApi.getLoginUser()
      loginUser.value = response.data
      saveUserToStorage(response.data)
      return response.data
    } catch (error: unknown) {
      console.error('获取用户信息失败:', error)
      loginUser.value = null
      saveUserToStorage(null)
      return null
    } finally {
      loading.value = false
    }
  }

  // 用户登录
  const login = async (loginData: UserLoginRequest) => {
    try {
      loading.value = true
      const response = await userApi.login(loginData)
      loginUser.value = response.data
      saveUserToStorage(response.data)
      message.success('登录成功')
      return response.data
    } catch (error: unknown) {
      console.error('登录失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 用户注册
  const register = async (registerData: UserRegisterRequest) => {
    try {
      loading.value = true
      const response = await userApi.register(registerData)
      message.success('注册成功')
      return response.data
    } catch (error: unknown) {
      console.error('注册失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 用户注销
  const logout = async () => {
    try {
      loading.value = true
      await userApi.logout()
      loginUser.value = null
      saveUserToStorage(null)
      message.success('退出登录成功')
    } catch (error: unknown) {
      console.error('退出登录失败:', error)
      // 即使接口调用失败，也要清除本地登录状态
      loginUser.value = null
      saveUserToStorage(null)
    } finally {
      loading.value = false
    }
  }

  // 清除用户信息
  const clearUser = () => {
    loginUser.value = null
    saveUserToStorage(null)
  }

  // 初始化store时恢复用户信息
  initUserFromStorage()

  return {
    // 状态
    loginUser,
    loading,

    // 计算属性
    isLogin,
    isAdmin,

    // 方法
    fetchLoginUser,
    login,
    register,
    logout,
    clearUser,
  }
})
